package com.nononsenseapps.feeder.processor.interceptor

import com.nononsenseapps.feeder.db.entity.FeedItem
import com.nononsenseapps.feeder.db.entity.ITEM_BODY_FORMAT_TYPE_HTML
import com.nononsenseapps.feeder.db.entity.ITEM_BODY_FORMAT_TYPE_NO_SET
import com.nononsenseapps.feeder.processor.Interceptor
import com.nononsenseapps.feeder.processor.ProcessContext
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import timber.log.Timber

class FormatInterceptor :Interceptor{

    override fun intercept(chain: Interceptor.Chain): FeedItem {
        val feed=chain.getFeed()
        val feedItem=chain.getFeedItem()
        val context=chain.getProcessContext()

        if(feedItem.bodyFormatType in arrayOf(
                ITEM_BODY_FORMAT_TYPE_NO_SET,
                ITEM_BODY_FORMAT_TYPE_HTML
            )){
            var bodyString=feedItem.description
            Timber.d("FormatInterceptor feedItemId:${feedItem.id}")
            if(feed.bodyReFormat){
                bodyString=formatBodyText(context.getDocument(bodyString),context,feedItem.id)
            }

            feedItem.description=bodyString
        }
        return chain.proceed(feed, feedItem)
    }

    companion object{
        val filterList= emptyList<String>()

        /**批配项 空行
        <p><String><br/></String></p>
        <p><br></p>
        <p><br/></p>
        <p>&nbsp;</p>
        <p><1112>&nbsp;</sfsf></p>
        <p style="class" dir="dfdf"><br></p>

        //不批配
        <p style="class" dir="dfdf"><img src="sdfsaf"><br></p>
        <p style="class" dir="dfdf"><img src="sdfsaf"/><aadadad><br></p>
         **/
        val pattenReplaces=mutableMapOf("<p\\b[^<>]*>(<\\w*>)?(<br[/]?>|&nbsp;)(</\\w*>)?</p>".toRegex() to "<br/>")
    }
}

fun formatBodyText(bodyText:String,feedItemId:Long):String{
   return formatBodyText(Jsoup.parse(bodyText),feedItemId=feedItemId)
}

fun formatBodyText(document: Document,context: ProcessContext?=null,feedItemId:Long):String{
    var bodyString = document.toString()
    FormatInterceptor.filterList.forEach{
        if(bodyString.contains(it)) {
            Timber.d("FormatInterceptor feedItemId:${feedItemId} String match :$it")
            bodyString = bodyString.replace(it, " ")
            context?.modifyFlag=true
        }
    }
    FormatInterceptor.pattenReplaces.forEach{ entity->
        if(bodyString.contains(entity.key)) {
            Timber.d("FormatInterceptor feedItemId:${feedItemId} patten match :${entity.key.pattern}")
            bodyString = entity.key.replace(bodyString, entity.value)
            context?.modifyFlag=true
        }
    }
    return bodyString
}